import { RequestTracker } from '../utils/requestTracker';
import PagePaintLog = App.PagePaintLog;

/**
 * 页面绘制时间
 */
export class PagePaint {
    private requestTracker: RequestTracker;
    constructor(requestTracker: RequestTracker) {
        this.requestTracker = requestTracker;
        this.init();
    }

    init() {
        if (PerformanceObserver) {
            let FP: PerformanceEntry | null = null;
            let FCP: PerformanceEntry | null = null;
            let FMP: PerformanceEntry  | null = null;
            let LCP: PerformanceEntry | null = null;

            // 监控性能指标 FP FCP
            const observerFPANDFCP = new PerformanceObserver(entryList => {
                const perfEntries = entryList.getEntries();
                for (const perfEntry of perfEntries) {
                    if (perfEntry.name === 'first-paint') {
                        FP = perfEntry;
                    } else if (perfEntry.name === 'first-contentful-paint') {
                        FCP = perfEntry;
                        observerFPANDFCP.disconnect(); // 断开监听
                    }
                }
            });
            observerFPANDFCP.observe({ entryTypes: ['paint'] });

            // 监控性能指标 FMP
            const observerFMP = new PerformanceObserver(entryList => {
                const perfEntries = entryList.getEntries();
                FMP =  perfEntries[0];
                observerFMP.disconnect();
            });
            observerFMP.observe({ entryTypes: ['element']});

            // 监听 LCP
            const observerLCP = new PerformanceObserver(entryList => {
                const perfEntries = entryList.getEntries();
                LCP = perfEntries[0];
            });
            observerLCP.observe({ entryTypes: ['largest-contentful-paint']});

            window.addEventListener('load', () => {
                setTimeout(() => {
                    // 暂停 LCP的监听
                    observerLCP.disconnect();
                    const log: PagePaintLog = {
                        type: 'paint',
                        FP: FP?.startTime,
                        FCP: FCP?.startTime,
                        FMP: FMP?.startTime,
                        LCP: LCP?.startTime
                    };
                    this.requestTracker.request(log);
                }, 3000);
            });
        }
    }
}
